package com.steve.xfood.controller;

import com.steve.xfood.config.ProjectUrlConfig;
import com.steve.xfood.constants.CookieConstant;
import com.steve.xfood.constants.RedisConstant;
import com.steve.xfood.dataobject.SellerInfo;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.service.SellerInfoService;
import com.steve.xfood.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 卖家登录和登出
 * @author steve
 * @date 2020/5/26 17:01
 */
@Controller
@RequestMapping("/seller")
public class SellerUserController {
    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    ProjectUrlConfig projectUrlConfig;

    /**
     * 卖家登录
     * 扫码登录访问路径：
     * https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http://sell.springboot.cn/sell/qr/oTgZpwdZi_KC40hZHU-YmlWogkHU&response_type=code&scope=snsapi_login&state=http://xfood.nat300.top/sell/wechat/qrUserInfo
     * 我的openid=o9AREv0fvuLNEJqM_-nJlqdRFh-g
     * @param openid
     * @param map
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, Map<String, Object> map,
                              HttpServletResponse response) {
        //1.openid去和数据库进行匹配
        SellerInfo sellerInfo = sellerInfoService.findSellerInfoByOpenid(openid);
        if(sellerInfo == null) {
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/sell/seller/order/list");
            return new ModelAndView("common/error", map);
        }
        String token = UUID.randomUUID().toString();
        //过期时间
        Integer expire = RedisConstant.EXPIRE;
        //2.设置token到redis
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token),openid,expire, TimeUnit.SECONDS);

        //3.设置token到cookie
        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);

        //这里需要重定向到（因为没有携带参数）订单列表页面，重定向地址要写绝对路径，不然会出错
        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");
    }

    /**
     * 用户登出
     */
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Map<String, Object> map) {
        //1.从cookie查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //2.清除redis的token
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
            //3.清除cookie的token
            CookieUtil.set(response,CookieConstant.TOKEN,null,0);
        }
        map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url", "/sell/seller/order/list");
        return new ModelAndView("common/success", map);

    }
}
